<template>
  <view class="work-content-form common-container">
    <wd-form custom-class="common-form" ref="formRef" :model="formModel">
      <wd-cell-group>
        <!-- <wd-picker :columns="columns" label="填写月份" v-model="value" @confirm="handleConfirm" /> -->
        <wd-datetime-picker
          type="year-month"
          :max-date="maxDate"
          v-model="formModel.dateCode"
          label="填写月份"
        />
        <wd-cell title="本月工作情况">
          <wd-textarea
            v-model="formModel.workLog"
            :maxlength="500"
            show-word-limit
            placeholder="请填写评价"
          />
        </wd-cell>
        <wd-cell title="下月工作计划">
          <wd-textarea
            v-model="formModel.nextWorkLog"
            :maxlength="500"
            show-word-limit
            placeholder="请填写评价"
          />
        </wd-cell>
      </wd-cell-group>
    </wd-form>
    <wd-button type="primary" @click="submitForm" :round="false" block>保存工作内容</wd-button>
  </view>
</template>

<script setup>
import WorkApi from '@/service/work'
import dayjs from 'dayjs'

const emits = defineEmits(['submit'])

const maxDate = new Date().getTime()

const initFormModel = {
  dateCode: maxDate,
  type: 'month',
  workLog: '',
  nextWorkLog: '',
}

const formRef = ref()
const formModel = ref({
  dateCode: maxDate,
  type: 'month',
  workLog: '',
  nextWorkLog: '',
})
const formKeyMap = {
  dateCode: '月份',
  workLog: '本月工作情况',
  nextWorkLog: '下月工作计划',
}

const submitForm = () => {
  let objKey = ''
  for (const key in formKeyMap) {
    if (!formModel.value[key]) {
      objKey = key
      break
    }
  }
  if (objKey) {
    uni.showToast({
      title: `${formKeyMap[objKey]}不能为空`,
      icon: 'none',
    })
    return false
  }

  formRef.value
    .validate()
    .then(async () => {
      const dateCode = dayjs(formModel.value.dateCode).format('YYYY-MM')
      const params = {
        ...formModel.value,
        dateCode,
      }
      const { code, result, message } = await WorkApi.addWork(params)
      if (code === 200 && result) {
        uni.showToast({
          icon: 'success',
          title: '添加成功',
        })
        formModel.value = initFormModel
        emits('submit')
      } else {
        uni.showToast({
          icon: 'error',
          title: message,
        })
      }
    })
    .catch((error) => {
      console.error(error)
    })
}
</script>

<script>
export default {
  options: {
    styleIsolation: 'shared',
  },
}
</script>

<style lang="scss">
@import '../../../style/common-form';

.work-content-form {
  /* stylelint-disable-next-line selector-class-pattern */
  :deep() .wd-textarea__count {
    background: none;
  }
}
</style>
